package com.kevin.common.config.date;


import com.kevin.common.config.json.JsonConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * spring mvc日期转换类 支持多种日期格式传入
 *
 * @author wh
 * @date 2021-03-16
 */
@Configuration
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {


    DateTimeFormatter ymFormatter = DateTimeFormatter.ofPattern("yyyy-MM");

    DateTimeFormatter ymdFormatter = DateTimeFormatter.ofPattern(JsonConfig.DEFAULT_DATE_FORMAT);

    DateTimeFormatter ymdHmFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    DateTimeFormatter ymdHmsFormatter = DateTimeFormatter.ofPattern(JsonConfig.DEFAULT_DATE_TIME_FORMAT);


    @Override
    public LocalDateTime convert(String source) {
        source = source.trim();
        if ("".equals(source)) {
            return null;
        }

        // 使用优先级最频繁,减少if次数
        if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            // yyyy-MM-dd HH:mm:ss
            return LocalDateTime.parse(source, ymdHmsFormatter);
        } else if (source.matches("^\\d{4}-\\d{1,2}$")) {
            // yyyy-MM
            return LocalDateTime.parse(source + "-01 00:00:00", ymFormatter);
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            // yyyy-MM-dd
            return LocalDateTime.parse(source + " 00:00:00", ymdFormatter);
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
            // yyyy-MM-dd HH:mm
            return LocalDateTime.parse(source + ":00", ymdHmFormatter);
        } else {
            throw new IllegalArgumentException("Invalid datetime value '" + source + "'");
        }
    }
}
